using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void DirectoryDelete(SqlString path)
    {
        Int16 errSeverity = 16;

        try
        {
            // Determine whether the directory exists.
            if (Directory.Exists(path.ToString()) == true)
            {
                // Try to delete the directory.
                DirectoryInfo di = new DirectoryInfo(path.ToString());
                di.Delete();
            }
            else
            {
                // Generate informational message that the directory did not exist.
                errSeverity = 10;
                Exception newEx = new Exception("Directory does not exist.");
                throw newEx;
            }
        }
        catch (Exception ex)
        {
            // Connect to server in event of error
            SqlConnection conn = new SqlConnection("context connection=true");
            conn.Open();

            // Generate error response to SQL Server
            string msg = string.Format("RAISERROR('{0}',{1},1)", ex.Message.Replace('\'', ' '), errSeverity);
            SqlCommand cmd = new SqlCommand(msg, conn);

            try
            {
                // Execute error on SQL Server
                SqlPipe sqlpipe = SqlContext.Pipe;
                sqlpipe.ExecuteAndSend(cmd);
                Exception newEx = new Exception(msg);
                throw newEx;
            }
            catch {} // Prevent error duplication
        }
    }
};
